<?php

namespace Home\Controller;

use Org\Util\Validate;

/**
 * 不用登录的公开对外页面
 * @author songanwei
 * @date 2015-12-31
 */
class PublicController extends ParentController {

    protected function _initialize() {
        $this->validateUtil = new \Org\Util\Validate();
    }

    /**
     * 获取图片验证码
     * @modify AmosZhong 2016-01-07
     */
    public function createpic() {
        createVcode();
    }

    /**
     * @description 后端管理人员登录操作
     * @modify songanwei 2015-12-31
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function login() {
        $this->checkLogout();
        $mobile = I('post.mobile', '', 'string');
        $password = I('post.password', '', 'string');
        $areaCode = I('post.areaCode', '86', 'string');

        // 密码是否有加密过
        if (isset($_COOKIE['mz_login_password']) && strlen($password) > 23) {
            // AES 解密
            $password = AESdncrypt($password);
        }

        //检查参数
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        $adminLoginLogic = A('Common/adminLogin', 'Logic');
        $hashPassword = hash('sha256', $password);
        $adminLogin = $adminLoginLogic->login($mobile, $hashPassword, true, $areaCode);

        // 生成cookie信息
        $guid = guidv4_for_openssl();
        $now = time();
        $RsaEncrypt = new \Org\Util\RSAEncrypt();
        $userSSID = $RsaEncrypt->meizhuEncrypt($adminLogin['id']);
        if (!$userSSID) {
            returnJson(500, 505);
        }
        $userSSPS = cookieUserSSPS($adminLogin['mobile'], $hashPassword, $now);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_UUID'), $guid);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_USSID'), $userSSID);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_USSPS'), $userSSPS);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_PSTM'), $now);


        //清除原有session数据
        session(null);
        // 存储基本信息到session
        session(C('USER_ID'), $adminLogin['id']);
        session(C('USER_NAME'), $adminLogin['name']);
        session(C('USER_MOBILE'), $adminLogin['mobile']);
        session(C('USER_HEAD'), $adminLogin['headpath']);
        returnJson(200, 200, 'success');
    }

    /**
     * @description 发送短信验证码
     * @modify songanwei 2015-12-31
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function sendCode() {
        //$this->checkLogout();
        $mobile = I('post.mobile');
        $areaCode = I('post.areaCode', '86', 'string');

        //检查参数
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        //检查手机号是否已注册
        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        if (empty($adminLogin)) {
            returnJson(403, 100);
        }
        //检查是否一分钟发送过
        $messageSendTime = session(C('RESET_PASSWORD_SEND_TIME'));
        if (!empty($messageSendTime) && !isOverMinute($messageSendTime, 1)) {
            returnJson(403, 107);
        }
        //发送短信验证码
        $token = getRandomNumber();
        $sessionId = session_id();
        session(C('RESET_PASSWORD_VCODE'), $token);
        session(C('RESET_PASSWORD_SEND_MOBILE'), $mobile);

        if ($areaCode == '86') {
            $messageSender = new \Org\Util\Sms();
            $messageSendResult = $messageSender->sendVocode($mobile, $token);
        } else {
            $yunPian = new \Org\Util\yunPian();
            $messageSendResult = $yunPian->sendVcode($areaCode, $mobile, $token);
        }

        if (empty($messageSendResult)) {
            returnJson(403, 151);
        }
        session(C('RESET_PASSWORD_SEND_TIME'), time());
        returnJson(200, 200, array('code' => $token));
    }

    /**
     * @description 检查短信验证码
     * @modify songanwei 2015-12-31
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function checkCode() {
        //$this->checkLogout();
        $mobile = I('post.mobile');
        $code = I('post.vcode');
        $areaCode = I('post.areaCode', '86', 'string');

        $sessionMobile = session(C('RESET_PASSWORD_SEND_MOBILE'));
        $sessionCode = session(C('RESET_PASSWORD_VCODE'));
        $messageSendTime = session(C('RESET_PASSWORD_SEND_TIME'));
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        $this->ajaxValidateReturn($this->validateUtil, $code, "notnull,notempty,vcode6");

        // 验证session参数是否存在
        if (empty($sessionMobile) || empty($sessionCode) || empty($messageSendTime)) {
            returnJson(403, 122, 'error');
        }
        // 验证手机是否与session存的一致
        if ($mobile != $sessionMobile) {
            returnJson(403, 122);
        }
        // 校验短信验证码5分钟过期
        if (isOverMinute($messageSendTime)) {
            returnJson(403, 153);
        }
        // 校验码正误
        if ($code != $sessionCode) {
            returnJson(403, 120, 'error');
        }

        // 校验成功,发送链接跳转
        $sessionId = session_id();
        session(C('RESET_PASSWORD_VALIDATE_PASSWORD'), true);
        $url = '/resetPassword.html?id=' . $sessionId . '&mobile=' . $mobile;
        returnJson(200, 200, $url);
    }

    /**
     * @description 重置密码
     * @modify songanwei 2015-12-31
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function resetPassword() {
        //$this->checkLogout();
        $mobile = I('post.mobile');
        $password = I('post.password');
        $areaCode = I('post.areaCode', '86', 'string');
        // 检查session内校验结果
        $resetValidatePass = session(C('RESET_PASSWORD_VALIDATE_PASSWORD'));
        if (empty($resetValidatePass)) {
            returnJson(403, 123);
        }
        // 校验手机号格式
        //$this->ajaxValidateReturn($this->validateUtil, $mobile, 'notnull,notempty,mobile');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        // 执行重置密码

        $adminLoginModel = D('AdminLogin');
        //检查是否存在此用户
        $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
        if (!$adminLogin) {
            returnJson(200, 100);
        }

        $result = $adminLoginModel->setPassword($adminLogin['id'], hash('sha256', $password));
        if ($result == false) {
            returnJson(403, 123);
        }        

        //清掉旧的登录信息
        session(null);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_UUID'), null);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_USSID'), null);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_USSPS'), null);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_PSTM'), null);
        
        returnJson(200, 200, 'success');
    }

    /**
     * @description 客栈开通申请
     * @modify songanwei 2015-12-31
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function apply() {
        //$this->checkLogout();

        $params = I('post.');
        $validateRule = array(
            'hotel' => 'notnull,notempty,nameLength20',
            'address' => 'notnull,notempty,nameLength20',
            //'mobile' => 'notnull,notempty,mobile',
            'name' => 'notnull,notempty,nameLength20',
            'from' => 'notnull,notempty,nameLength20',
            'cityId' => 'notnull,notempty,id',
            'districtId' => 'notnull,notempty,id',
            'verify' => 'notnull,notempty',
            'currencyId' => 'notnull,notempty,id',
        );
        //检查参数
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        // 校验图片验证码
        $verify = $params['verify'];
        if (empty(checkVcode($verify))) {
            returnJson(403, 201);
            return;
        }
        $hotelName = $params['hotel'];
        $cityName = $params['address'];
        $mobile = $params['mobile'];
        $userName = $params['name'];
        $from = $params['from'];
        $universalTimeId = I('post.universalTime', '5', 'intval');
        $areaCode = I('post.areaCode', '86', 'string');
        $countryId = isset($params['countryId']) ? $params['countryId'] : null;
        $universalTimeId = isset($universalTimeId) && !empty($universalTimeId) ? $universalTimeId : '5';
        $cityId = $params['cityId'];
        $districtId = $params['districtId'];
        $currencyId = $params['currencyId'];

        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        //检查参数
        $hotelApplyLogic = A('Common/HotelApply', 'Logic');
        //$hotelApplyLogic->apply($hotelName, $cityName, $mobile, $userName, 0, $from, $universalTimeId, $areaCode, $countryId, $cityId, $districtId);
        $hotelApplyLogic->addApplyHotel($hotelName, $cityName, $mobile, $userName, $universalTimeId, $areaCode, $countryId, $cityId, $districtId, $currencyId);

        returnJson(200, 200);
    }
	/**
     * @description 美住与锁掌柜同步
     * @modify songanwei 2016-12-20
     */
	public function syn(){
		$this->checkLogout();
		$mobile = I('post.mobile', '', 'string');
        $password = I('post.password', '', 'string');
        $areaCode = I('post.areaCode', '86', 'string');
        $this->ajaxValidateReturn($this->validateUtil, $mobile, 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));

        // 密码是否有加密过
        if (isset($_COOKIE['mz_login_password']) && strlen($password) > 23) {
            // AES 解密
            $password = AESdncrypt($password);
        }

        //检查参数
		Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('MANAGE_SYN_URL'));
        $client->setEncryptMode(3);
        $sendData = array(
            'flag' => 'uclbrt',
            'time' => time(),
            'mobile' => $mobile,
            'areaCode' => $areaCode,
            'password' => $password
        );
        $clientData = $client->Login($sendData);

		if($clientData == 100){
			returnJson(403, 100);
		}
		if($clientData == 101){
			returnJson(403, 101);
		}
		$hashPassword = hash('sha256', $password);
		$adminLoginModel = D('AdminLogin');
		$adminInfoModel = D('AdminInfo');
		$haveAdmin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
		if($haveAdmin){
			//有账号的操作
			$adminInfo = $adminInfoModel->getInfoByUser($haveAdmin['id']);
			$result = $haveAdmin['id'];
			$clientData = array(
				'id' => $clientData['id'],
				'name' => $haveAdmin['name'],
				'headpath' => $adminInfo['headpath'],
			);
		}else{
			//没有账号就生成一个账号
			$result = $adminLoginModel->addInfo($mobile,$hashPassword,$clientData['name'],$areaCode);
			$adminLoginModel->setEndtime($result,date("Y-m-d H:i:s",strtotime("+1 week",time())));
			$adminLoginModel->setStatus($result,1);
			$adminInfoModel->addInfo($result);
            //发送短信
            if ($areaCode == '86') {
                $smsUtil = new \Org\Util\Sms();
                $smsUtil->sendSynAccount($mobile);
            } else {
                // 云片
                $smsUtil = new \Org\Util\yunPian();
                $smsUtil->yunPianSendSynAccount($areaCode, $mobile);
            }
            

			cookie('newAccount', "new",5);
		}
		
		// 生成cookie信息
        $guid = guidv4_for_openssl();
        $now = time();
        $RsaEncrypt = new \Org\Util\RSAEncrypt();
        $userSSID = $RsaEncrypt->meizhuEncrypt($result);
        if (!$userSSID) {
            returnJson(500, 505);
        }
        $userSSPS = cookieUserSSPS($mobile, $hashPassword, $now);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_UUID'), $guid);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_USSID'), $userSSID);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_USSPS'), $userSSPS);
        cookie(C('COOKIE_SERVER_REMEMBER_ME_PSTM'), $now);
        //清除原有session数据
        session(null);
        // 存储基本信息到session
		session('master_id',$clientData['id']);
        session(C('USER_ID'), $result);
        session(C('USER_NAME'), $clientData['name']);
        session(C('USER_MOBILE'), $mobile);
        session(C('USER_HEAD'), $clientData['headpath']);
        returnJson(200, 200);
		
	}

}
